package com.example.demo.controller;

import com.example.demo.channel.service.ChannelInterface;
import com.example.demo.channel.service.MicroPayChannel;
import com.example.demo.core.DynamicLoadUtil;
import com.example.demo.core.MyLoader5;
import com.example.demo.core.UserApplicationContext;
import com.sun.tools.attach.VirtualMachine;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态加载完成不停机部署
 */
@RestController
public class DynamicLoadController {

    //动态加载class文件目录信息(不包括包名信息)
    @Value("${file.path}")
    private String filePath;

    //动态加载jar信息
    @Value("${lib.path}")
    private String libPath;

    // 通道map集合
    // 通道map集合
    private static Map<String, ChannelInterface> channelMap = new ConcurrentHashMap();



    /**
     * 动态 加载 class jar 信息
     *
     * @return 返回加载class信息
     * @throws Exception
     */
    @RequestMapping("/loadBeanToContainer")
    public Map loadBeanToContainer() throws Exception {
        ApplicationContext applicationContext = UserApplicationContext.getApplicationContext();
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
        //DynamicLoadUtil.loopJarToClassPath(libPath, beanFactory.getBeanClassLoader());
        List<Class> aClass = DynamicLoadUtil.loadClass(filePath, new MyLoader5(filePath,beanFactory.getBeanClassLoader()));
        //List<Class> aClass = DynamicLoadUtil.loadClass(filePath, beanFactory.getBeanClassLoader());
        vm = VirtualMachine.attach(pid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("path",filePath);
        jsonObject.put("check","com.example.demo.channel.service.Impl");
        jsonObject.put("classList",aClass);
        //vm.loadAgent("C:\\Users\\Administrator\\Desktop\\dev\\lib\\demo-0.0.1-SNAPSHOT.jar", jsonObject.toString());
        vm.loadAgent("Y:\\other\\git\\demo_back\\target\\demo-0.0.1-SNAPSHOT.jar", jsonObject.toString());

        Map map = new HashMap();
        if (!CollectionUtils.isEmpty(aClass)) {
            aClass.stream().filter(r -> (!r.isInterface() && !Modifier.isAbstract(r.getModifiers())) ).forEach(r -> {
                BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(r);
                if (beanFactory.containsBean(r.getName())) {
                    //移除bean防止重复注册bean
                    beanFactory.removeBeanDefinition(r.getName());
                }
                beanFactory.registerBeanDefinition(r.getName(), beanDefinitionBuilder.getRawBeanDefinition());
                Object o = beanFactory.getBean(r.getName());
                if(o instanceof ChannelInterface){
                    put(r.getSimpleName().toLowerCase(), (ChannelInterface) o);
                }else if(o instanceof MicroPayChannel){
                    MicroPayChannel c = (MicroPayChannel)o;
                    System.out.println(c);
                }
                map.put(aClass.indexOf(r), r.getName());
            });
            System.out.println("load class success");
        }
        return map;
    }


    public static void main(String[] args) throws Exception {
        loadBeanToContainer2();
    }
    public static Map loadBeanToContainer2() throws Exception {
        String filePath = "C:\\\\Users\\\\Administrator\\\\Desktop\\\\dev\\\\class2\\\\";
        //DynamicLoadUtil.loopJarToClassPath(libPath, beanFactory.getBeanClassLoader());
        List<Class> aClass = DynamicLoadUtil.loadClass(filePath, new MyLoader5("",null));
        //List<Class> aClass = DynamicLoadUtil.loadClass(filePath, beanFactory.getBeanClassLoader());
        vm = VirtualMachine.attach(pid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("path",filePath);
        jsonObject.put("check","com.example.demo.channel.service.Impl");
        jsonObject.put("classList",aClass);
        //vm.loadAgent("C:\\Users\\Administrator\\Desktop\\dev\\lib\\demo-0.0.1-SNAPSHOT.jar", jsonObject.toString());
        vm.loadAgent("Y:\\other\\git\\demo_back\\target\\demo-0.0.1-SNAPSHOT.jar");

        Map map = new HashMap();

        return map;
    }


    private static String classesPath;
    private static VirtualMachine vm;
    private static String pid;

    static {
        // 当前进程pid
        String name = ManagementFactory.getRuntimeMXBean().getName();
        pid = name.split("@")[0];
        System.out.println("java agent:pid:{}" + pid);
    }


    private static void init() throws Exception {
        vm = VirtualMachine.attach(pid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("path","C:\\Users\\Administrator\\Desktop\\dev\\lib\\");
        jsonObject.put("check","com.example.demo");
        jsonObject.put("classList","com.example.demo");
        //vm.loadAgent("C:\\Users\\Administrator\\Desktop\\dev\\lib\\demo-0.0.1-SNAPSHOT.jar", jsonObject.toString());
        vm.loadAgent("Y:\\other\\git\\demo_back\\target\\demo-0.0.1-SNAPSHOT.jar", jsonObject.toString());
    }

    /**
     * 统一管理通道bean信息
     *
     * @param type 通道类型信息
     * @param c    class
     */
    public static void put(String type, ChannelInterface c) {
        channelMap.put(type, c);
    }


    /**
     * 动态获取通道信息
     *
     * @param type 通道类型
     * @return 返回通道信息
     */
    public ChannelInterface queryChannelByType(String type) {
        return channelMap.get(type);

    }

}
